package com.hadwinling.blog.util;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author Hadwinling
 * @create 2020-04-22 19:18
 */
@Component
public class FileUpload {
    /**
     * @param uploadFile:传入要上传的图片呢
     * @return 存到七牛云的，并返回的地址
     * @throws IOException
     */
    public static String FileUploadToQiNiu(MultipartFile uploadFile) throws IOException {
        //对文件名的处理
        String fileName = uploadFile.getOriginalFilename();//得到文件的名字
        String suffix = fileName.substring(fileName.lastIndexOf(".") - 1);//对文件名进行处理， suffix ：文件的后缀
        String uuid = UUID.randomUUID().toString().toUpperCase().replace("-", "");//生成UUID
//        fileName = uuid + suffix;
        fileName = uuid ;

        //选择地区
        Configuration cfg = new Configuration(Region.huanan());
        //文件上传管理器
        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证，然后准备上传
        String accessKey = "BG7D1BBXIantlOqdAfR1lfwJVexRPtwyLsEdHHWr";
        String secretKey = "W6Yx8MUuJyTFOn7H7wy9UaCwLR0Dlz2Ir8v3Fe49";

        //选择要上传的空间
        String bucket = "hadwinling";

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        /**
         * fileName：文件名
         * uploadFile.getBytes()：将传入的文件转为字节流进行上传
         */
        Response response = uploadManager.put(uploadFile.getBytes(), fileName, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        //在main页面中显示图片http://img.hadwinling.top/%E7%BE%8E%E9%A3%9F.jpg
        String imgurl = "http://img.hadwinling.top/"+putRet.key;
//        System.out.println(imgurl);
        return imgurl;
    }
}
